<template>
    <el-row>
        <el-button type="primary" @click="openUpload" size="small">上传文件</el-button>
        <el-button type="success" @click="to_newDir" size="small">新建目录</el-button>
        <el-button type="info" @click="download" size="small">下载文件</el-button>
    </el-row>
    <el-row style="margin: 20px;">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/index' }">{{ loginUser.username }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ currentDir.directoryName }}</el-breadcrumb-item>
        </el-breadcrumb>
    </el-row>
    <el-table :data="tableData" style="width: 100%" align="center">
        <el-table-column prop="checked" width="28">
            <template #default="checkScope">
                <el-checkbox v-model="checkScope.row.checked"></el-checkbox>
            </template>
        </el-table-column>
        <el-table-column prop="style" label="文件类型" width="80" align="center">
            <template #default="scope">
                <img :src="'/images/' + scope.row.style + '.png'" class="style_image" />
            </template>
        </el-table-column>
        <el-table-column prop="fileName" label="名称" width="180" align="center" :formatter="nameFormatter"></el-table-column>
        <el-table-column prop="fileSize" label="大小" width="180" align="center" :formatter="sizeFormatter"></el-table-column>
        <el-table-column prop="createTime" label="上传时间" align="center" :formatter="dateFormatter"></el-table-column>
    </el-table>

    <div v-html="converter.makeHtml(markData)" v-highlight></div>

    <el-dialog v-model="dialogVisible" title="上传文件" width="30%" :before-close="handleClose">
        <span>
            <el-upload ref="fileUpload" class="upload-demo" drag action="http://localhost:8082/file/upload" multiple
                :data="uploadData" :auto-upload="false" :on-error="handleError" :on-success="handleSuccess">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    Drop file here or <em>click to upload</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        jpg/png files with a size less than 500kb
                    </div>
                </template>
            </el-upload>
        </span>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handlerSubmit">
                    上传
                </el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="newDir" title="新建目录" width="20%" :before-close="dirHandleClose">
        <span>
            <el-form>
                <el-form-item label="文件夹名称">
                    <el-input v-model="dirName" placeholder="请输入文件夹名称"></el-input>
                </el-form-item>
            </el-form>
        </span>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="newDir = false">取消</el-button>
                <el-button type="primary" @click="submitNewDir">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>

import axios from 'axios'
import showdown from "showdown";


export default {
    data() {
        const converter = new showdown.Converter();
        converter.setOption("tables", true);
        return {
            dialogVisible: false,
            newDir: false,
            dirName: '',
            tableData: [],
            uploadData: {},
            converter,
            markData: ''
        }
    },
    computed: {
        currentDir() {
            return this.$store.getters.getCurDir
        },
        loginUser() {
            return this.$store.getters.getLoginUser
        },
    },
    watch: {
        'currentDir.directoryName': {
            handler() {
                this.getData()
            }
        }
    },
    methods: {
        getData() {
            axios('http://localhost:8082/file/getFiles?id=' + this.currentDir.id)
                .then(res => {
                    this.tableData = res.data.data
                    this.tableData.forEach(f => {
                        f.style = this.getStyle(f.fileName)
                    })
                })
        },
        getStyle(name) {
            const fromIndex = name.lastIndexOf('.') + 1
            return fromIndex == -1 ? 'floder' : name.substring(fromIndex)
        },
        // 格式化文件大小的显示
        sizeFormatter(row, column, cellValue, index) {
            let size = parseInt(cellValue)
            let units = ["B", "KB", "MB", "GB"]
            let i = 0
            while (size > 1024) {
                size /= 1024
                i++
            }
            return size.toFixed(2) + units[i]
        },
        // 格式化文件名显示
        nameFormatter(row, column, cellValue, index) {
            // if (row.style === 'folder') {
            //     return '<router-link :to="{name: \'FileInfo\', params: {name: \'' + cellValue + '\'}}">' + cellValue + '</router-link>'
            // } else {
            //     return cellValue
            // }
            const toIndex = cellValue.lastIndexOf('.')
            return cellValue.substring(0, toIndex == -1 ? cellValue.length : toIndex)
        },
        dateFormatter(row, column, cellValue, index) {
            const date = new Date(cellValue)
            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
                date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
        },
        openUpload() {
            this.dialogVisible = true;
        },
        handlerSubmit() {
            this.uploadData = {
                userId: this.loginUser.id,
                directoryId: this.currentDir.id
            }
            this.$refs.fileUpload.submit();
        },
        handleError(err) {
            console.log(err);
            this.$message({
                message: '上传失败',
                type: 'warning'
            });
        },
        handleSuccess(res) {
            console.log(res);
            if (res.code === 0) {
                this.$message({
                    message: '上传失败',
                    type: 'warning'
                });
            }
        },
        to_newDir() {
            this.newDir = true;
        },
        submitNewDir() {
            fetch('http://localhost:8082/directory/newDir?userId=' +
                this.$store.getters.getLoginUser.id + "&dirName=" + this.dirName, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
            }).then(res => res.json())
                .then(data => {
                    console.log(data);
                    if (data.code == 1) {
                        this.$message({
                            message: '新建目录成功',
                            type: 'success'
                        });
                        this.newDir = false;
                    }

                })
                .catch(err => console.log(err));
        },
        handleClose() {
            this.dialogVisible = false;
            this.$refs.fileUpload.clearFiles();
        },
        dirHandleClose() {
            this.newDir = false;
            this.dirName = '';
        },
        handleChange(row) {
            console.log("修改了", row);
            if (row.checked) { // 被选中

            }
        },
        download() {
            const downloadFiles = this.tableData.filter(item => item.checked)
            if (downloadFiles.length > 1) {
                this.$message({
                    message: '一次只能下载一个文件',
                    type: 'warning'
                });
            } else if (downloadFiles.length == 0) {
                this.$message({
                    message: '请选择要下载的文件',
                    type: 'warning'
                });
            } else {
                const downloadFile = downloadFiles[0]
                const url = 'http://localhost:8082/file/download?id=' + downloadFile.id
                window.location.href = url
            }
        },
        //转换markdown为html语言
        compileMarkDown(val) {
            return this.converter.makeHtml(val);
        },
        getMarkData() {
            axios('http://localhost:8082/file/readFile?id=3').then(res => {
                console.log(res);
                this.markData = res.data.data
            })
        }
    },
    mounted() {
        this.getData()
        this.getMarkData()
    },
}
</script>

<style>
.style_image {
    width: 30px;
    vertical-align: middle;
}

.el-dialog__header,
.el-dialog__footer {
    text-align: center;
}
</style>